from flask import Blueprint, request, jsonify
from src.models.models import db, Word, WordSet, Example
from datetime import datetime

words_bp = Blueprint('words', __name__)

@words_bp.route('/words', methods=['GET'])
def get_words():
    """获取单词列表"""
    try:
        set_id = request.args.get('set_id', type=int)
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        
        query = Word.query
        if set_id:
            query = query.filter_by(set_id=set_id)
            
        words = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        result = []
        for word in words.items:
            word_dict = word.to_dict()
            # 获取例句
            examples = Example.query.filter_by(word_id=word.id).all()
            word_dict['examples'] = [ex.to_dict() for ex in examples]
            result.append(word_dict)
        
        return jsonify({
            'success': True,
            'data': result,
            'pagination': {
                'page': words.page,
                'pages': words.pages,
                'per_page': words.per_page,
                'total': words.total
            }
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@words_bp.route('/words/<int:word_id>', methods=['GET'])
def get_word(word_id):
    """获取单个单词详情"""
    try:
        word = Word.query.get_or_404(word_id)
        word_dict = word.to_dict()
        
        # 获取例句
        examples = Example.query.filter_by(word_id=word.id).all()
        word_dict['examples'] = [ex.to_dict() for ex in examples]
        
        return jsonify({
            'success': True,
            'data': word_dict
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@words_bp.route('/word-sets', methods=['GET'])
def get_word_sets():
    """获取词汇集列表"""
    try:
        word_sets = WordSet.query.all()
        return jsonify({
            'success': True,
            'data': [ws.to_dict() for ws in word_sets]
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@words_bp.route('/today-plan', methods=['GET'])
def get_today_plan():
    """获取今日学习计划（10个单词）"""
    try:
        user_id = request.args.get('user_id', type=int)
        if not user_id:
            return jsonify({'success': False, 'error': 'user_id is required'}), 400
        
        # 简化版：随机返回10个单词
        words = Word.query.limit(10).all()
        result = []
        for word in words:
            word_dict = word.to_dict()
            examples = Example.query.filter_by(word_id=word.id).limit(2).all()
            word_dict['examples'] = [ex.to_dict() for ex in examples]
            result.append(word_dict)
        
        return jsonify({
            'success': True,
            'data': result
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

